package com.ericsson.enap.modules.autoCheck.thread;

import com.ericsson.enap.modules.autoCheck.entity.NetAutoCheck;
import com.ericsson.enap.modules.autoCheck.entity.VisAutoCheckLog;
import com.ericsson.enap.modules.autoCheck.entity.VisExcelModuleDetail;
import com.ericsson.enap.modules.autoCheck.service.EopsTemplateScheduleService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class EopsTemplateExecuteCmdThread implements Runnable {

	private Logger log;
	private String fetchDate;
	private CountDownLatch latch;
	private NetAutoCheck net;
	private EopsTemplateScheduleService scheduleService;
	private List<VisExcelModuleDetail> visExcelModuleDetails;
	private String tpXmlPathTxt;

	public EopsTemplateExecuteCmdThread(NetAutoCheck net, List<VisExcelModuleDetail> visExcelModuleDetails,
										EopsTemplateScheduleService scheduleService, CountDownLatch latch, String fetchDate, Logger log, String tpXmlPathTxt) {
		this.net = net;
		this.visExcelModuleDetails = visExcelModuleDetails;
		this.fetchDate = fetchDate;
		this.scheduleService = scheduleService;
		this.latch = latch;
		this.log = log;
		this.tpXmlPathTxt = tpXmlPathTxt;
	}

	public EopsTemplateExecuteCmdThread() {

	}

	@Override
	public void run() {
		try {
			dotask();
		} catch (Exception e) {
			log.error("dotask error", e);
		} finally {
			latch.countDown();
		}

	}

	private void dotask() {
		log.info("===============sub thread ====netId:" + net.getId() + " run start");
		for (VisExcelModuleDetail moduleDetail : visExcelModuleDetails) {
			String command = "/usr/bin/perl -w /opt/Ericsson/core/bin/eops.pl";
			command += " -ip " + net.getIp4() + " -user " + net.getUsername() + " -password '" + net.getPassword()
					+ "' -conf_file " + tpXmlPathTxt + moduleDetail.getExcelId() + "_"
					+ moduleDetail.getModuleId() + ".txt -rootpassword '" + net.getRootPassword() + "'";
			log.info("netId========" + net.getId() + "command======" + command);
			VisAutoCheckLog autoCheckLog = execAutoTemplateCheckCmd(command, net.getId(), moduleDetail.getExcelId());
			/*autoCheckLog.setTemplateType(moduleDetail.getTemplateType().toLowerCase().substring(0,
					moduleDetail.getTemplateType().length() - 3));*/
			if("3".equals(moduleDetail.getTemplateType())) {
				autoCheckLog.setTemplateType("inspection");
			} else if("6".equals(moduleDetail.getTemplateType())) {
				autoCheckLog.setTemplateType("alarm");
			} else if("5".equals(moduleDetail.getTemplateType())) {
				autoCheckLog.setTemplateType("log");
			}

			// 过滤命令前的其它信息 start
			if (null != autoCheckLog && StringUtils.isNotBlank(autoCheckLog.getCheckResult())
					&& !autoCheckLog.getCheckResult().equals("exception")) {
				String filterResult = filterGarbageMsg(moduleDetail, autoCheckLog);
				if (null != filterResult) {
					autoCheckLog.setCheckLog(filterResult);
				}
			}
			//// 过滤命令前的其它信息 end
			if (StringUtils.isNotBlank(autoCheckLog.getCheckLog())) {
				scheduleService.insertAutoCheckLog(autoCheckLog);
			}
		}

		log.info("================= AutoCheckTemplateServiceTask end  ========");
	}

	public VisAutoCheckLog execAutoTemplateCheckCmd(String command, Integer netId, Integer excelId) {
		Process proc = null;
		String[] cmd = new String[3];
		cmd[0] = "sh";
		cmd[1] = "-c";
		cmd[2] = command;
		// System.out.println(cmd[2]);
		BufferedReader br = null;
		String line = null;
		StringBuilder sb = new StringBuilder();
		VisAutoCheckLog autoCheckLog = new VisAutoCheckLog();
		autoCheckLog.setNetId(netId);
		autoCheckLog.setExcelId(excelId);
		autoCheckLog.setCheckTime(this.fetchDate);

		try {
			proc = Runtime.getRuntime().exec(cmd);// 测试时需要注释掉

			br = new BufferedReader(new InputStreamReader(proc.getInputStream()), 10 * 1024 * 1024);// 测试时需要注释掉
			 //br = readFile("F:/text.txt");//测试代码
			Thread.sleep(200);
			while ((line = br.readLine()) != null) {

				sb.append(line).append("||");

				 //log.info("-------------"+line+"------------------");
				// 成功
				if (line.contains("EOPS RUN SUCCESS")) {
					autoCheckLog.setCheckResult("ok");
				} else if (line.contains("<font color=\"red\">")) { // 异常 低于门限
					autoCheckLog.setCheckResult("Nok");
				} else {
					if(!"ok".equals(autoCheckLog.getCheckResult()) && !"Nok".equals(autoCheckLog.getCheckResult())) {
						autoCheckLog.setCheckResult("exception"); // 出错 程序没有正确执行
					}

				}
			}
			autoCheckLog.setCheckLog(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (proc != null) {
				proc.destroy();
			}
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return autoCheckLog;
	}

	/**
	 * 过滤返回结果中的无用头信息（ok,Nok状态数据）
	 * 
	 * @param moduleDetail
	 * @param autoCheckLog
	 * @return String 过滤后的结果
	 */
	public String filterGarbageMsg(VisExcelModuleDetail moduleDetail, VisAutoCheckLog autoCheckLog) {
		if (StringUtils.isNotBlank(autoCheckLog.getCheckLog()) && !"".equals(autoCheckLog.getCheckLog())
				&& null != moduleDetail && StringUtils.isNotBlank(moduleDetail.getConfCmd())) {
			int startSize = autoCheckLog.getCheckLog().indexOf(moduleDetail.getConfCmd())
					+ moduleDetail.getConfCmd().length();
			return autoCheckLog.getCheckLog().substring(startSize);
		}
		return null;
	}

	public BufferedReader readFile(String path) {
		FileInputStream fileInputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;
		try {
			fileInputStream = new FileInputStream(path);
			inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
			reader = new BufferedReader(inputStreamReader);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return reader;
	}

	public static void main(String args[]) {
		/*VisExcelModuleDetail moduleDetail = new VisExcelModuleDetail();
		moduleDetail.setConfCmd("pdc_kpi.pl -n 1 -i 15 -l ");
		VisAutoCheckLog autoCheckLog = new VisAutoCheckLog();
		autoCheckLog.setCheckLog(
				"Password: ||Wind River Linux 5.0.1.35||Installed: Mon Dec  5 23:37:19 CST 2016||Last login: Thu Nov 14 11:47:31 2019 from 10.204.211.229||||=== DALMME13BER nmcsys@eqm01s0fp2 ANCB ~ # ||||=== DALMME13BER nmcsys@eqm01s0fp2 ANCB ~ # pdc_kpi.pl -n 1 -i 15 -l ||||Day                                 : 14              ||Time                                : 11:47           ||attach_gsm                          : 1.7%            ||intra_rau_gsm                       : 1.7%            ||israu_gsm                           : 16.5%           ||paging_gsm                          : 11.7%           ||pdp_activation_gsm                  : 0.1%            ||pdp_cut_off_gsm                     : 1.1%            ||attach_wcdma                        : 0.0%            ||intra_rau_wcdma                     : 0.0%            ||israu_wcdma                         : 0.0%            ||paging_wcdma                        : 0.0%            ||pdp_activation_wcdma                : 0.0%            ||pdp_cut_off_wcdma                   : 0.0%            ||rab_establishment_wcdma             : 0.0%            ||service_request_wcdma               : 0.0%            ||attach_lte                          : 0.7%            ||bearer_establishment_lte            : 0.0%            ||csfb_1xrtt_lte                      : 0.0%            ||csfb_wg_lte                         : 3.4%            ||gbr_bearer_activation_lte           : 0.2%            ||inter_isc_tau_lte                   : 1.8%            ||inter_mme_tau_lte                   : 0.0%            ||intra_isc_tau_lte                   : 3.5%            ||intra_mme_tau_lte                   : 0.1%            ||irat_ho_mme_source_lte              : 0.0%            ||irat_ho_mme_target_lte              : 0.0%            ||location_update_lte                 : 0.1%            ||paging_lte                          : 0.9%            ||paging_sms_lte                      : 4.3%            ||s1_handover_lte                     : 6.0%            ||service_request_lte                 : 0.0%            ||srvcc_g_lte                         : 1.1%            ||srvcc_w_lte                         : 0.0%            ||x2_handover_lte                     : 0.0%            ||downlink_avg_gb                     : 240.134         ||downlink_kpps_gb                    : 8.603           ||downlink_mbps_gb                    : 16.527          ||uplink_avg_gb                       : 110.850         ||uplink_kpps_gb                      : 9.558           ||uplink_mbps_gb                      : 8.476           ||downlink_avg_iu                     : 0.0             ||downlink_kpps_iu                    : 0.000           ||downlink_mbps_iu                    : 0.000           ||uplink_avg_iu                       : 0.0             ||uplink_kpps_iu                      : 0.000           ||uplink_mbps_iu                      : 0.000           ||downlink_avg_gn                     : 247.495         ||downlink_kpps_gn                    : 8.832           ||downlink_mbps_gn                    : 17.487          ||uplink_avg_gn                       : 110.850         ||uplink_kpps_gn                      : 9.558           ||uplink_mbps_gn                      : 8.476           ||downlink_avg_s4                     : 0.0             ||downlink_kpps_s4                    : 0.000           ||downlink_mbps_s4                    : 0.000           ||uplink_avg_s4                       : 0.0             ||uplink_kpps_s4                      : 0.000           ||uplink_mbps_s4                      : 0.000           ||pdp_gsm                             : 69676           ||sau_gsm                             : 105601          ||sds_gsm                             : 67767           ||pdp_wcdma                           : 0               ||sau_wcdma                           : 0               ||sds_wcdma                           : 0               ||active_bearer_lte                   : 1205178         ||active_pdn_lte                      : 1196621         ||sau_lte                             : 842837          ||sau_s102_lte                        : 0               ||sau_sgs_lte                         : 853372          ||sub_lte                             : 957224          ||=== DALMME13BER nmcsys@eqm01s0fp2 ANCB ~ # ||SYSTEM-RUN echo ' ||||Day                                 : 14              ||Time                                : 11:47           ||attach_gsm                          : 1.7%            ||intra_rau_gsm                       : 1.7%            ||israu_gsm                           : 16.5%           ||paging_gsm                          : 11.7%           ||pdp_activation_gsm                  : 0.1%            ||pdp_cut_off_gsm                     : 1.1%            ||attach_wcdma                        : 0.0%            ||intra_rau_wcdma                     : 0.0%            ||israu_wcdma                         : 0.0%            ||paging_wcdma                        : 0.0%            ||pdp_activation_wcdma                : 0.0%            ||pdp_cut_off_wcdma                   : 0.0%            ||rab_establishment_wcdma             : 0.0%            ||service_request_wcdma               : 0.0%            ||attach_lte                          : 0.7%            ||bearer_establishment_lte            : 0.0%            ||csfb_1xrtt_lte                      : 0.0%            ||csfb_wg_lte                         : 3.4%            ||gbr_bearer_activation_lte           : 0.2%            ||inter_isc_tau_lte                   : 1.8%            ||inter_mme_tau_lte                   : 0.0%            ||intra_isc_tau_lte                   : 3.5%            ||intra_mme_tau_lte                   : 0.1%            ||irat_ho_mme_source_lte              : 0.0%            ||irat_ho_mme_target_lte              : 0.0%            ||location_update_lte                 : 0.1%            ||paging_lte                          : 0.9%            ||paging_sms_lte                      : 4.3%            ||s1_handover_lte                     : 6.0%            ||service_request_lte                 : 0.0%            ||srvcc_g_lte                         : 1.1%            ||srvcc_w_lte                         : 0.0%            ||x2_handover_lte                     : 0.0%            ||downlink_avg_gb                     : 240.134         ||downlink_kpps_gb                    : 8.603           ||downlink_mbps_gb                    : 16.527          ||uplink_avg_gb                       : 110.850         ||uplink_kpps_gb                      : 9.558           ||uplink_mbps_gb                      : 8.476           ||downlink_avg_iu                     : 0.0             ||downlink_kpps_iu                    : 0.000           ||downlink_mbps_iu                    : 0.000           ||uplink_avg_iu                       : 0.0             ||uplink_kpps_iu                      : 0.000           ||uplink_mbps_iu                      : 0.000           ||downlink_avg_gn                     : 247.495         ||downlink_kpps_gn                    : 8.832           ||downlink_mbps_gn                    : 17.487          ||uplink_avg_gn                       : 110.850         ||uplink_kpps_gn                      : 9.558           ||uplink_mbps_gn                      : 8.476           ||downlink_avg_s4                     : 0.0             ||downlink_kpps_s4                    : 0.000           ||downlink_mbps_s4                    : 0.000           ||uplink_avg_s4                       : 0.0             ||uplink_kpps_s4                      : 0.000           ||uplink_mbps_s4                      : 0.000           ||pdp_gsm                             : 69676           ||sau_gsm                             : 105601          ||sds_gsm                             : 67767           ||pdp_wcdma                           : 0               ||sau_wcdma                           : 0               ||sds_wcdma                           : 0               ||active_bearer_lte                   : 1205178         ||active_pdn_lte                      : 1196621         ||sau_lte                             : 842837          ||sau_s102_lte                        : 0               ||sau_sgs_lte                         : 853372          ||sub_lte                             : 957224          ||=== DALMME13BER nmcsys@eqm01s0fp2 ANCB ~ ' | grep sau_lte | cut -d ':' -f 2 | cut -d ' ' -f 2||842837||||||=== DALMME13BER nmcsys@eqm01s0fp2 ANCB ~ # exit||||logout||Connection to 10.203.54.161 closed.||||EOPS RUN SUCCESS||");
		// System.out.println(filterGarbageMsg(moduleDetail,autoCheckLog));*/

	}
}
